package com.cac.demo.controller.gkinterface;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cac.demo.service.deliveryPlan.DeliveryPlanService;
import com.cac.demo.service.gkinterface.WorkService;
import com.cac.demo.service.materialScan.WmsDeliverPlanService;
import com.cac.demo.service.msBulkyItems.MsBulkyItemsService;
import com.cac.demo.service.msConsole.MsConsoleService;
import com.cac.demo.util.AsyncLog;
import com.cac.demo.util.CreatMsgId;
import com.cac.demo.util.ExceptionToStirng;
import com.cac.demo.util.XmlReadUtil;
import com.cac.demo.util.adapter.ComUtil;
import com.cac.demo.util.adapter.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//http://172.17.101.150:8080/sortSys/sortGkReceiveInterface/ReceiveDispath
@RestController
@RequestMapping("/sortGkReceiveInterface")
@Slf4j
public class ErpGkReceiveInterface {

    @Autowired
    private WorkService workService;
    @Autowired
    private Environment environment;
    @Autowired
    private WmsDeliverPlanService wmsDeliverPlanService;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private MsConsoleService msConsoleService;
    @Autowired
    private MsBulkyItemsService msBulkyItemsService;
    @Autowired
    private DeliveryPlanService deliveryPlanService;
    @Autowired
    private AsyncLog asyncLog;
    File xmlFile = null;

    /**
     * @throws
     * @Title: fileReceiveTest
     * @Description: 工控网接收园区网 - 接收文件流
     * @param: @param BData
     * @param: @param files
     * @param: @return
     */
    @PostMapping("/ReceiveDispath")
    public ResponseMsg<String> receiveDispath(@RequestParam("BData") String BData, @RequestParam("file") List<MultipartFile> files) {

        String func = null;
        log.info("=====================================================");
        long systime = System.currentTimeMillis();//yyyyMMddhh+systime
        ResponseMsg responseMsg = new ResponseMsg();
        log.info("园区网下发工控网文件流接收测试，时间：" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));

        //设置文件存放路径
        String fileDir = environment.getProperty("pathProperty.path");

        JSONArray paramJsonObjectArray = new JSONArray();
        String LogId = ComUtil.getId();
        //园区网下发日志
        HashMap issuedTest = new HashMap();
        issuedTest.put("id", LogId);
        //7-21 xiaojian 新增日志表主键
        HashMap logMap = new HashMap();
        logMap.put("msErpExchangeLogId", LogId);
        String rslt = "", retcode = "1";
        FileInputStream fileInputStream = null;
        //事务管理
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            if (BData != null || "".equals(BData)) {
                String decodedBytes = new String();
                decodedBytes = Base64.decodeStr(BData, "UTF-8");

                String DeBData = decodedBytes;
                log.info("ReceiveDispath=======================业务参数：" + DeBData);
                JSONObject paraJsonObject = JSONObject.parseObject(DeBData);

                func = paraJsonObject.getString("func");
                String param = paraJsonObject.getString("param");
                paramJsonObjectArray = JSONArray.parseArray(param);
                log.info("========ReceiveDispath===============园区网下发===============================");
                //园区网下发日志
                issuedTest.put("BData", DeBData);
                issuedTest.put("type", func);
                issuedTest.put("msgId", paraJsonObject.get("msgId"));

                //2023-06-17 yebo 保存日志信息新 10-17注释
             /*   logMap.put("func", func);
                logMap.put("msgId", paraJsonObject.get("msgId"));
                workService.insertErpLog(logMap);
                logMap.put("bdata", DeBData);
                workService.updateErpBdata(logMap);*/
                try {
                    issuedTest.put("nowTime", com.cac.demo.util.DateUtil.nowTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            if (null != files && files.size() > 0) {
                //日志：文件路径
                String path = this.downloadFile(fileDir, files);
                issuedTest.put("file", path);
                fileInputStream = new FileInputStream(xmlFile);
                XmlReadUtil xmlReadUtil = new XmlReadUtil(fileInputStream);
                //下月计划
                if (func != null && "package_month_send".equals(func)) {
                    log.info("园区网下发月计划>>>>>>>>>>>>>>>>>>>>>>>>>>>start");
                    //获取数据工作包任务
                    List list1 = xmlReadUtil.getAttributesByTagName("MES_ASS_WP_WORKPACKAGE_PLAN");
                    String groupNo = ComUtil.getId();
                    for (int i = 0; i < list1.size(); i++) {
                        HashMap tmpMap = (HashMap) list1.get(i);
                        tmpMap.put("IMPORT_GROUP_NO", groupNo);
                        workService.insertWorkPackage(tmpMap);
                    }
                    //获取ao任务
                    List list2 = xmlReadUtil.getAttributesByTagName("MES_ASSAOTASK");
                    for (int i = 0; i < list2.size(); i++) {
                        HashMap tmpMap = (HashMap) list2.get(i);
                        tmpMap.put("IMPORT_GROUP_NO", groupNo);
                        workService.insertMesAoTask(tmpMap);
                    }
                    //获取物料信息
                    List list3 = xmlReadUtil.getAttributesByTagName("MES_ASS_SETOUT_MATERIAL");
                    for (int i = 0; i < list3.size(); i++) {
                        HashMap tmpMap = (HashMap) list3.get(i);
                        tmpMap.put("IMPORT_GROUP_NO", groupNo);
                        workService.insertMesMaterial(tmpMap);
                    }
                    //修改bill ao 关联关系
                    workService.updateMatchBill(groupNo);
                    workService.updateAoTask(groupNo);

                    responseMsg.setMessage("接收成功！");
                    log.info("园区网下发月计划>>>>>>>>>>>>>>>>>>>>>>>>>>>end");
                } else if (func != null && "package_task_send".equals(func)) {//下双周计划
                    log.info("园区网下发周计划>>>>>>>>>>>>>>>>>>>>>>>>>>>start");
                    //获取数据工作包任务
                    List list1 = xmlReadUtil.getAttributesByTagName("MES_ASS_WP_WORKPACKAGE_PLAN");
                    for (int i = 0; i < list1.size(); i++) {
                        HashMap tmpMap = (HashMap) list1.get(i);
                        log.info(">>>>>>>>>>>>>>>>>>>>>>>>." + tmpMap.get("MES_ASS_WP_WORKPACKAGE_PLAN_ID"));
                        workService.updateWorkPackage(tmpMap);
                        try {
                            //根据taskaoid向ao表插入IP
                            msConsoleService.algorithmTaskByAoId((String) tmpMap.get("MES_ASSAOTASK_ID"));
                        }catch (Exception e){
                            System.out.println("根据taskaoid向ao表插入IP失败");
                            e.printStackTrace();
                        }
                        //分配任务
                        msConsoleService.algorithmTaskByPackageId((String) tmpMap.get("MES_ASS_WP_WORKPACKAGE_PLAN_ID"));

                        //将此工作包下无法分拣的大件自动分拣
                        msBulkyItemsService.bulkySortedAuto((String) tmpMap.get("MES_ASS_WP_WORKPACKAGE_PLAN_ID"));
                    }
                    responseMsg.setMessage("接收成功！");
                    log.info("园区网下发周计划>>>>>>>>>>>>>>>>>>>>>>>>>>>end");
                } else if (func != null && "process_changes".equals(func)) {//AO工艺更改更改物料  AO详情那的下发
                    String groupNo = ComUtil.getId();

                    //获取ao任务
                    List aoList = xmlReadUtil.getAttributesByTagName("MES_ASSAOTASK");
                    for (int i = 0; i < aoList.size(); i++) {
                        HashMap tmp = (HashMap) aoList.get(i);
                        tmp.put("IMPORT_GROUP_NO", groupNo);
                        //插入新增的AO信息
                        workService.updateAoByProcessChange(tmp);
                    }
                    //获取物料信息
                    List materialList = xmlReadUtil.getAttributesByTagName("MES_ASS_SETOUT_MATERIAL");
                    for (int i = 0; i < materialList.size(); i++) {
                        HashMap tmp = (HashMap) materialList.get(i);
                        tmp.put("IMPORT_GROUP_NO", groupNo);
                        workService.insertAoChangeTmp(tmp);
                        workService.updateMaterialByProcessChange(tmp);
                    }
                    HashMap delMap = new HashMap();
                    delMap.put("IMPORT_GROUP_NO", groupNo);
                    //删除已作废的物料
                    workService.matchBillBak(delMap);
                }
                //修改下达日计划时间
                else if (func != null && "package_daily_send".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_ASSAOTASK");
                    log.info("修改下达日计划时间:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        workService.updateDailyTime(tmpMap);
                    }
                }
                //零件预上账
                else if (func != null && "ERP-101-preConfirmLj".equals(func)) {
                    log.info("零件预上账：");
                    String xlimitLotNo = "";
                    //插入mds_item表
                    List list1 = xmlReadUtil.getAttributesByTagName("MDS_ITEM");
                    List list2 = xmlReadUtil.getAttributesByTagName("WMS_QUALITY_INFO");
                    List deliverys = xmlReadUtil.getAttributesByTagName("WMS_DELIVERY_PLAN");
                    for (int i = 0; i < list1.size(); i++) {
                        HashMap tmpMap = (HashMap) list1.get(i);
                        wmsDeliverPlanService.AddMdsItem(tmpMap);
                    }
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        HashMap map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        map.put("func", func);

                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", map.get("wms_delivery_plan_id"));
                        //2023-11-07 yebo 修改，如果质量文件里面限用信息没有，则取字符串里面的
                        xlimitLotNo = (String)map.get("x_limit_lot_no");
                        wmsDeliverPlanService.insertAdvancePosting(map);
                    }
                    for (int i = 0; i < list2.size(); i++) {
                        HashMap map = (HashMap) list2.get(i);
                        //2023-11-07 yebo 修改，如果质量文件里面限用信息没有，则取字符串里面的
                        map.put("xLimitLotNo",xlimitLotNo);
                        wmsDeliverPlanService.insertWmsQualityInfo(map);

                    }
                    //2023-11-07 yebo 修改接收备注 从文件获取
                    for(int i=0;i<deliverys.size();i++){
                        HashMap delivery = (HashMap) deliverys.get(i);
                        wmsDeliverPlanService.updateDeliveryRemarkOnPreConfirm(delivery);
                    }
                }
                //成品预上账
                else if (func != null && "ERP-101-preConfirmCp".equals(func)) {
                    log.info("成品预上账：");
                    String xlimitLotNo = "";
                    //插入mds_item表
                    List list1 = xmlReadUtil.getAttributesByTagName("MDS_ITEM");
                    List list2 = xmlReadUtil.getAttributesByTagName("WMS_QUALITY_INFO");
                    List deliverys = xmlReadUtil.getAttributesByTagName("WMS_DELIVERY_PLAN");
                    for (int i = 0; i < list1.size(); i++) {
                        HashMap tmpMap = (HashMap) list1.get(i);
                        wmsDeliverPlanService.AddMdsItem(tmpMap);
                    }
                    //新增PLAN表数据
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        HashMap map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        map.put("func", func);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", map.get("wms_delivery_plan_id"));
                        //2023-11-07 yebo 修改，如果质量文件里面限用信息没有，则取字符串里面的
                        xlimitLotNo = (String)map.get("x_limit_lot_no");
                        wmsDeliverPlanService.insertAdvancePosting(map);
                    }
                    for (int i = 0; i < list2.size(); i++) {
                        HashMap map = (HashMap) list2.get(i);
                        //2023-11-07 yebo 修改，如果质量文件里面限用信息没有，则取字符串里面的
                        map.put("xLimitLotNo",xlimitLotNo);
                        wmsDeliverPlanService.insertWmsQualityInfo(map);
                    }
                    //2023-11-07 yebo 修改接收备注 从文件获取
                    for(int i=0;i<deliverys.size();i++){
                        HashMap delivery = (HashMap) deliverys.get(i);
                        wmsDeliverPlanService.updateDeliveryRemarkOnPreConfirm(delivery);
                    }
                }
                //标准件预上账
                else if (func != null && "ERP-101-preConfirmBzj".equals(func)) {
                    log.info("标准件预上账：");
                    String xlimitLotNo = "";
                    //插入mds_item表
                    List list1 = xmlReadUtil.getAttributesByTagName("MDS_ITEM");
                    List list2 = xmlReadUtil.getAttributesByTagName("WMS_QUALITY_INFO");
                    List deliverys = xmlReadUtil.getAttributesByTagName("WMS_DELIVERY_PLAN");
                    for (int i = 0; i < list1.size(); i++) {
                        HashMap tmpMap = (HashMap) list1.get(i);
                        wmsDeliverPlanService.AddMdsItem(tmpMap);
                    }
                    //新增PLAN表数据
                    for (int i = 0; i < paramJsonObjectArray.size(); i++) {
                        HashMap map = JSON.parseObject(paramJsonObjectArray.get(i).toString(), HashMap.class);
                        map.put("func", func);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", map.get("wms_delivery_plan_id"));
                        map.put("erp_delivery_type","CL");
                        //2023-11-07 yebo 修改，如果质量文件里面限用信息没有，则取字符串里面的
                        xlimitLotNo = (String)map.get("x_limit_lot_no");
                        wmsDeliverPlanService.insertPreConfirmBzj(map);
                    }
                    for (int i = 0; i < list2.size(); i++) {
                        HashMap map = (HashMap) list2.get(i);
                        //2023-11-07 yebo 修改，如果质量文件里面限用信息没有，则取字符串里面的
                        map.put("xLimitLotNo",xlimitLotNo);
                        wmsDeliverPlanService.insertWmsQualityInfo(map);
                    }
                    //2023-11-07 yebo 修改接收备注 从文件获取
                    for(int i=0;i<deliverys.size();i++){
                        HashMap delivery = (HashMap) deliverys.get(i);
                        wmsDeliverPlanService.updateDeliveryRemarkOnPreConfirm(delivery);
                    }
                }

                //2022-11-7 MES-101扫码移交
                else if (func != null && "MES-101-ShopMaterialDelivery".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_ASS_ACTUAL_MATERIAL");
                    log.info("MES-101扫码移交:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        tmpMap.put("logId",issuedTest.get("msgId"));
                        wmsDeliverPlanService.shopMaterialDelivery(tmpMap);

                        HashMap aLog = new HashMap();
                        aLog.put("businessVal",tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        aLog.put("busniessCol","wms_delivery_plan_id");
                        aLog.put("taskName","MES-101扫码移交");
                        aLog.put("taskType","MES-101-ShopMaterialDelivery");
                        asyncLog.insertAsyncLog(aLog);
                        //此操作提前到101扫码移交了 2023-11-1 等那周周四部署后移除此标签
                        wmsDeliverPlanService.MakeMaterialCheck(tmpMap);
                    }
                }
                //MES取消移交
                else if (func != null && "MES-101-FenjianCancelDelivery".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_ASS_ACTUAL_MATERIAL");
                    List newlist = new ArrayList();
                    log.info("MES-101撤销移交:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = new HashMap();
                        tmpMap.put("wmsDeliveryPlanId", ((HashMap) list.get(i)).get("WMS_DELIVERY_PLAN_ID"));
                        newlist.add(tmpMap);
                    }
                    deliveryPlanService.MESCancelDelivery(newlist);
                }
                //MES-101现场驳回
                else if (func != null && "MES-101-ShopReturnMaterial".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_ASS_ACTUAL_MATERIAL");
                    log.info("MES-101现场驳回:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        wmsDeliverPlanService.ShopReturnMaterial(tmpMap);
                    }
                }
                //MES-101专业厂接收
                else if (func != null && "MES-101-ShopMaterialRece".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_MATERIAL_RECE_L");
                    log.info("MES-101专业厂接收:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        wmsDeliverPlanService.ShopMaterialRece(tmpMap);
                        log.info("2023-11-12 yebo 增加校验，专业厂接收后，判断物料是否生成流水，没有则调用出库");
                        //判断是否出库，若出库则 重新出库
                        int c = wmsDeliverPlanService.queryIsExistsOutTransaction(tmpMap);
                        if(c==0){//没有出库
                            HashMap aLog = new HashMap();
                            aLog.put("businessVal",tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                            aLog.put("busniessCol","wms_delivery_plan_id");
                            aLog.put("taskName","MES-101专业厂接收");
                            aLog.put("taskType","MES-101-ShopMaterialRece");
                            asyncLog.insertAsyncLog(aLog);
                            wmsDeliverPlanService.MakeMaterialCheck(tmpMap);
                        }
                    }
                }
                //MES-101物料正常退库
                else if (func != null && "101-ERP-itemBackToMsms4LjCp".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_MATERIAL_RECE_L");
                    log.info("MES-101物料正常退库:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        wmsDeliverPlanService.MaterialReturn(tmpMap);
                    }
                }
                //MES-101物料故障退库
                else if (func != null && "MES-101-MaterialGzReturn".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_MATERIAL_RECE_L");
                    log.info("MES-101物料故障退库:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        wmsDeliverPlanService.MaterialGzReturn(tmpMap);
                    }
                }
                //MES-101报废退库
                else if (func != null && "MES-101-MaterialBfReturn".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_MATERIAL_RECE_L");
                    log.info("MES-101报废退库:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        wmsDeliverPlanService.MaterialBfReturn(tmpMap);
                    }
                }

                //MES-101四联单退库
                else if (func != null && "MES-101-MaterialSldReturn".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_MATERIAL_RECE_L");
                    log.info("MES-101四联单退库:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        wmsDeliverPlanService.MaterialSldReturn(tmpMap);
                    }
                }//MES-101二次配套
                else if (func != null && "MES-101-SendSecondMatch".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_MATERIAL_RECE_L");
                    log.info("MES-101二次配套");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan");
                        issuedTest.put("businessCol", "wms_delivery_plan_id");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        wmsDeliverPlanService.SecondMatch(tmpMap);
                    }
                }
                //MES-101物料变更
                else if (func != null && "MES-101-SenceMaterialBg".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_ASS_SETOUT_MATERIAL");
                    log.info("MES-101物料变更:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        wmsDeliverPlanService.SenceMaterialBg(tmpMap);
                    }
                }
                //MES-101现场物料检验  ---2023-10-19注意，此func实际上是101扫码移交的时候也会调用此func 用于下账  2023-11-1部署后，MES那就不会调用此接口了
                else if (func != null && "MES-101-MakeMaterialCheck".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("MES_MATERIAL_RECE_L");
                    log.info("MES-101现场物料:");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_inv_out_allotment_id");
                        issuedTest.put("businessCol", "wms_inv_out_allotment");
                        issuedTest.put("businessVal", tmpMap.get("WMS_INV_OUT_ALLOTMENT_ID"));
                        tmpMap.put("logId",LogId);
                        //此操作提前到101扫码移交了
                      //  wmsDeliverPlanService.MakeMaterialCheck(tmpMap);
                    }
                }//MES-101 扫码移交确认
                else if (func != null && "MES-101-DeliveryConfirm".equals(func)) {
                    List list = xmlReadUtil.getAttributesByTagName("WMS_DELIVERY_PLAN");
                    for (int i = 0; i < list.size(); i++) {
                        HashMap tmpMap = (HashMap) list.get(i);
                        issuedTest.put("businessTab", "wms_delivery_plan_id");
                        issuedTest.put("businessCol", "wms_delivery_plan");
                        issuedTest.put("businessVal", tmpMap.get("WMS_DELIVERY_PLAN_ID"));
                        workService.DeliveryConfirm(tmpMap);
                    }
                }
            }
            //事务提交
            platformTransactionManager.commit(transaction);
            retcode = "1";
            rslt = "操作成功";
            logMap.put("wmsResult", rslt);
        } catch (DuplicateKeyException ex) {
            //  ex.printStackTrace();
            platformTransactionManager.rollback(transaction);
            retcode = "1";
            rslt = "操作成功,当前数据已经接收！请不要重复传递";
            logMap.put("wmsResult", rslt);
        } catch (Exception e) {
            e.printStackTrace();
            responseMsg.setMessage("接收失败！失败原因：" + e.getMessage());
            platformTransactionManager.rollback(transaction);
            rslt = ExceptionToStirng.getExceptionToString(e);
            logMap.put("wmsResult", rslt);
            log.info(rslt);
            if (rslt.length() > 200) {
                rslt = rslt.substring(0, 200);
            }
            retcode = "0";
        } finally {
            //yebo 最后记录操作日志
            issuedTest.put("result", rslt);
            issuedTest.put("failMsg", rslt);
            issuedTest.put("system", "ERP");
            issuedTest.put("retCode", retcode);
            workService.issuedTest(issuedTest);
            //7-21 新增日志详细记录 10-17注释
            //logMap.put("retCode", issuedTest.get("retCode"));
            // workService.updateErpLog(logMap);
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //2023-05-25 yebo 新增反馈回调ERP，反馈处理结果
            JSONArray fdarrays = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            String msgId = CreatMsgId.getMsgId();
            jsonObject.put("msgId", issuedTest.get("msgId"));
            fdarrays.add(jsonObject);
            workService.resultBackToErp(fdarrays, msgId);
        }
        return responseMsg;
    }

    private String downloadFile(String fileDir, List<MultipartFile> files) {

        String newDir = null;

        try {
            // 在项目路径下按日期创建文件夹
            // 日期
            String dateDirName = DateUtil.format(new Date(), "yyyy-MM-dd");
            // 文件存放路径，
            fileDir = fileDir + dateDirName;
            new File(fileDir).mkdirs();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 下载文件
        try {
            String filePath = "";
            for (MultipartFile multipartFile : files) {
                log.info("文件名：" + multipartFile.getOriginalFilename());
                // 文件本地存放路径
                filePath = fileDir + "/" + multipartFile.getOriginalFilename();
                multipartFile.transferTo(new File(filePath));
            }
            File zipFile = new File(filePath);
            ZipUtil.unzip(zipFile);
            newDir = zipFile.getAbsolutePath().replace(".zip", "");
            File caseNoFilePath = new File(newDir);
            // 得到解压后的xml
            for (File file : caseNoFilePath.listFiles()) {
                if (!file.isDirectory()) {
                    if (file.getName().indexOf(".xml") > 0) {
                        xmlFile = file;
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return newDir;
        }
    }
}
